<script setup>
  import { ref, watch } from 'vue';
  import TodoHeader from './components/TodoHeader.vue'
  import TodoFooter from './components/TodoFooter.vue'
  import TodoMain from './components/TodoMain.vue'
  const list = ref(
  JSON.parse(localStorage.getItem('list')) || [
    { id: 1, name: '吃饭' },
    { id: 2, name: '睡觉' },
  ]
);

  const addTodo = (todoWork) => {
  if (!todoWork.trim()) return;
  list.value.unshift({
    id: +new Date(),
    name: todoWork,
  });
};
 
const deleteTodo = (id) => {
  list.value = list.value.filter(item => item.id !== id);
};
 
const clearTodos = () => {
  list.value = [];
};
 
// 监听 list 变化并持久化到 localStorage
watch(
  list,
  (newValue) => {
    localStorage.setItem('list', JSON.stringify(newValue));
  },
  { deep: true }
);
</script>

<template>
  <TodoHeader @add="addTodo"></TodoHeader>
  <TodoMain @del="deleteTodo" :list="list"></TodoMain>
  <TodoFooter @clear="clearTodos" :list="list"></TodoFooter>
</template>

<style scoped></style>
